package main

import (
	"bytes"
	"devserv"
	"gentk"
	"github.com/garyburd/redigo/redis"
	"log"
	"net/http"
	"rhelper"
	"time"
)

const (
	serverUrl = "http://server1.vesync.com:4002"
)

func main() {
	log.Println("start test ...")
	rhelper.InitRedis("127.0.0.1:6379")
	//testGetPowerReport()
	//testResetDev()
	//testSoftRestore()
	//testSetTrigger()
	//testDelTrigger()
	//testLoadTrigger()
	//testClearTriggerCount()
	//testLoadTriggerCount()
	//message.SendGmail("1052441607@qq.com", "hellow wrold")
	//testRedis("riguang")
	//testSetCtlFlags()
	// getCurrentDateTime()
	//testExpire()
	setOnlineDev()
	//ClearOnlineDev()
	return
}

func testExpire() {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	rconn.Send("MULTI")
	rconn.Send("SADD", rhelper.OnlineDev+"test", "123456789")
	rconn.Send("EXPIRE", rhelper.OnlineDev+"test", 60)

	_, err := rconn.Do("EXEC")
	if err != nil {
		log.Println("save2DB failed, save controller data error:", err)
	}
}

func setOnlineDev() {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	rconn.Send("MULTI")
	rconn.Send("HMSET", rhelper.ControllerHash+"123456", "status", "online", "serverId", "test")

	rconn.Send("SADD", rhelper.OnlineDev+"test", "123456")
	rconn.Send("EXPIRE", rhelper.OnlineDev+"test", 100)
	_, err := rconn.Do("EXEC")
	if err != nil {
		log.Println("save2DB failed, save controller data error:", err)
	}
}

func ClearOnlineDev() {
	clearOnlineDevLuaScript := `local members = redis.call('SMEMBERS', KEYS[1])
						  for k,member in pairs(members) do
						  redis.call('HMSET', KEYS[2]..member,"status","offline","serverId","")
						  end
						  redis.call('DEL', KEYS[1])
						 `

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	var getScript = redis.NewScript(2, clearOnlineDevLuaScript)
	getScript.Do(rconn, rhelper.OnlineDev+"test", rhelper.ControllerHash)
}

func testPowerReport() {

	report := devserv.PowerReportMsg{}
	report.Energy = "873"
	report.Duration = "183"

	c := devserv.Controller{}
	c.Id = "1234567899"

	c.SavePowerReportNew(report)
}

func testGetPowerReport() {
	//reports := userserv.GetReports("566ee603-ffff-ff7f-ffff-ff7fffffff7f", "2015112401", "2015112718")
	//log.Println("reports", reports)
}

func testResetDev() {
	var jsonStr = []byte(`{"cid":"baaccf38-d4c5-4668-9111-d93691a3a456"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/resetDev", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000009")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testSoftRestore() {
	var jsonStr = []byte(`{"cid":"048c6439-d7ac-434b-ab82-fe4ce2192945"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/softRestore", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000009")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

type Trigger struct {
	Cid               string  `json:"cid"`
	Above             float64 `json:"above"`
	Below             float64 `json:"below"`
	AboveAction       bool    `json:"aboveAction"`
	BelowAction       bool    `json:"belowAction"`
	IsClosePlug       bool    `json:"isClosePlug"`
	IsSendMail        bool    `json:"isSendMail"`
	IsPushNotify      bool    `json:"isPushNotify"`
	AboveTriggerCount int     `json:"aboveTriggerCount"`
	belowTriggerCount int     `json:"BelowTriggerCount"`
}

func testSetTrigger() {
	var jsonStr = []byte(`{"cid":"79cdbd5b-6e65-4965-b234-d85d0b4a1e6e",
		"above":20, "below":0, "aboveAction":true, "belowAction":false, "isClosePlug":true, "isSendMail":false, "isPushNotify":true}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/setTrigger", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testDelTrigger() {
	var jsonStr = []byte(`{"cid":"79cdbd5b-6e65-4965-b234-d85d0b4a1e6e"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/deleteTrigger", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testLoadTrigger() {
	var jsonStr = []byte(`{"cid":"79cdbd5b-6e65-4965-b234-d85d0b4a1e6e"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/loadTrigger", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testClearTriggerCount() {
	var jsonStr = []byte(`{"cid":"79cdbd5b-6e65-4965-b234-d85d0b4a1e6e"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/clearTriggerCount", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testLoadTriggerCount() {
	var jsonStr = []byte(`{"cid":"79cdbd5b-6e65-4965-b234-d85d0b4a1e6e"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/loadTriggerCount", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

func testRedis(account string) {
	log.Printf("account:%s,", account)

	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	id, err := redis.String(rconn.Do("HGET", rhelper.AccountHash+account, "id"))
	if err != nil && err != redis.ErrNil {
		log.Println("verifyAccount err:", err)
		return
	}

	log.Println("verifyAccount id:", id)

}

type Flags struct {
	Cid  string `json:"cid"`
	Flag string `json:"flag"`
	Set  string `json:"set"`
	Uri  string `json:"uri"`
}

func testSetCtlFlags() {
	var jsonStr = []byte(`{"cid":"048c6439-d7ac-434b-ab82-fe4ce2192945","flag":"0", "set":0, "uri":"/setCtlFlags"}`)
	client := &http.Client{Timeout: time.Second * 60}
	req, err := http.NewRequest("GET", serverUrl+"/setCtlFlags", bytes.NewBuffer(jsonStr))

	token := gentk.GenTK("1000001")
	req.Header.Add("tk", token)

	resp, err := client.Do(req)
	if err != nil {
		log.Println("err: ", err)
		return
	}

	if resp.StatusCode != 200 {
		log.Println("resp.StatusCode != 200")
		return
	}

	errcode := resp.Header.Get("error")
	if errcode != "" {
		log.Println("errorcode: ", errcode)
		return
	}

	body := make([]byte, 1024)
	read, err := resp.Body.Read(body)
	if err != nil && read < 1 {
		log.Println("read message body err: ", err)
		return
	}

	body = body[:read]
	log.Println("body: ", string(body))
}

type DeviceDateTime struct {
	Error        int
	Weekday      int
	Year         int
	Month        int
	Day          int
	MilliSeconds int
}

func getCurrentDateTime() *DeviceDateTime {
	dt := DeviceDateTime{}
	now := time.Now()
	dt.Weekday = int(now.UTC().Weekday())
	dt.Month = int(now.UTC().Month())
	dt.Year = now.UTC().Year()
	dt.Day = now.UTC().Day()

	middleNigh := time.Date(dt.Year, time.Month(dt.Month),
		dt.Day, 0, 0, 0, 0, time.UTC)
	d := (now.Sub(middleNigh))
	log.Println("d: ", d)
	dt.MilliSeconds = int(d.Nanoseconds() / 1000000)
	return &dt
}
